<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <link rel="shortcut icon" type="image/ico" href="favicon.ico" />
  <link rel="stylesheet" href="../slick.grid.css" type="text/css"/>
  <link rel="stylesheet" href="../css/smoothness/jquery-ui-1.11.3.custom.css" type="text/css"/>
  <link rel="stylesheet" href="../plugins/slick.headermenu.css" type="text/css"/>
  <link rel="stylesheet" href="../controls/slick.columnpicker.css" type="text/css"/>
  <link rel="stylesheet" href="examples.css" type="text/css"/>
  <style>
    /**
     * Style the drop-down menu here since the plugin stylesheet mostly contains structural CSS.
     */

    .slick-header-menu {
      border: 1px solid #718BB7;
      background: #f0f0f0;
      padding: 2px;
      -moz-box-shadow: 2px 2px 2px silver;
      -webkit-box-shadow: 2px 2px 2px silver;
      z-index: 20;
    }


    .slick-header-menuitem {
      padding: 2px 4px;
      border: 1px solid transparent;
      border-radius: 3px;
    }

    .slick-header-menuitem:hover {
      border-color: silver;
      background: white;
    }

    .slick-header-menuitem-disabled {
      border-color: transparent !important;
      background: inherit !important;
    }

    .icon-help {
      background-image: url(../images/help.png);
    }
  </style>
</head>
<body>
<div style="position:relative">
  <div style="width:500px;">
    <div id="myGrid" style="width:100%;height:500px;"></div>
  </div>

  <div class="options-panel">
      <h2>Demonstrates:</h2>
      <p>
        This example demonstrates using the <b>Slick.Plugins.HeaderMenu</b> plugin to add drop-down menus to column
        headers.  (Hover over the headers.)
      </p>
      <hr>
      <h3>Auto-align option</h3>
      <p>
        Auto-align (defaults to True), will calculate whether it has enough space to show the drop menu to the right. 
        If it calculates that the drop menu is to fall outside of the viewport, it will automatically align the drop menu to the left.        
      </p>
      <hr>
      <h3>Auto-Align Header Menu Drop</h3>
      <button onclick="autoAlignMenu(true)">ON</button>
      <button onclick="autoAlignMenu(false)">OFF</button>
      <h2>View Source:</h2>
      <ul>
          <li><A href="https://github.com/6pac/SlickGrid/blob/master/examples/example-plugin-headermenu.html" target="_sourcewindow"> View the source for this example on Github</a></li>
      </ul>
  </div>
</div>

<script src="../lib/jquery-1.11.2.min.js"></script>
<script src="../lib/jquery.event.drag-2.3.0.js"></script>

<script src="../slick.core.js"></script>
<script src="../slick.grid.js"></script>
<script src="../plugins/slick.headermenu.js"></script>
<script src="../controls/slick.columnpicker.js"></script>

<script>
  var data = [];
  var grid;
  var headerMenuPlugin;
  var columns = [
    {id: "title", name: "Title", field: "title", width: 90},
    {id: "duration", name: "Duration", field: "duration", sortable: true, width: 90},
    {id: "%", name: "% Complete", field: "percentComplete", sortable: true, width: 90},
    {id: "start", name: "Start", field: "start"},
    {id: "finish", name: "Finish", field: "finish"},
    {id: "effort-driven", name: "Effort Driven", field: "effortDriven"}

  ];

  for (var i = 0; i < columns.length; i++) {
    columns[i].header = {
      menu: {
        items: [
          {
            iconImage: "../images/sort-asc.gif",
            title: "Sort Ascending",
            disabled: !columns[i].sortable,
            command: "sort-asc"
          },
          {
            iconImage: "../images/sort-desc.gif",
            title: "Sort Descending",
            disabled: !columns[i].sortable,
            command: "sort-desc"
          },
          {
            title: "Hide Column",
            command: "hide",
            tooltip: "Can't hide this column"
          },
          {
            iconCssClass: "icon-help",
            title: "Help",
            command: "help"
          }
        ]
      }
    };
  }

  // keep a copy of all column for the array of visible columns
  var visibleColumns = columns;

  var options = {
    columnPicker: {
      columnTitle: "Columns"
    },
    enableColumnReorder: false,
    multiColumnSort: true
  };

  var executeSort = function(cols) {
		data.sort(function (dataRow1, dataRow2) {
        for (var i = 0, l = cols.length; i < l; i++) {
          var field = cols[i].sortCol.field;
          var sign = cols[i].sortAsc ? 1 : -1;
          var value1 = dataRow1[field], value2 = dataRow2[field];
          var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
          if (result != 0) {
            return result;
          }
        }
        return 0;
      });
      grid.invalidate();
      grid.render();
	};

	var removeColumnByIndex = function(array, index) {
    return array.filter(function (el, i) {
      return index !== i;
    });
  };

  function autoAlignMenu(isEnabled) {
    headerMenuPlugin.setOptions({ autoAlign: isEnabled });
  }

  $(function () {
    data = [];
    for (var i = 0; i < 500; i++) {
      data[i] = {
        title: "Task " + i,
        duration: Math.round(Math.random() * 25) + " days",
        percentComplete: Math.round(Math.random() * 100),
        start: "01/01/2009",
        finish: "01/05/2009",
        effortDriven: (i % 5 == 0)
      };
    }

    grid = new Slick.Grid("#myGrid", data, columns, options);
    var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);
    headerMenuPlugin = new Slick.Plugins.HeaderMenu({});

    grid.onSort.subscribe(function (e, args) {
      executeSort(args.sortCols);
		});

    headerMenuPlugin.onCommand.subscribe(function(e, args) {
			if(args.command === "hide") {
				var columnIndex = grid.getColumnIndex(args.column.id);
        visibleColumns = removeColumnByIndex(visibleColumns, columnIndex);
        grid.setColumns(visibleColumns);
	// Fix hidden sort column when multiColumnSort = true
          grid.setSortColumns(grid.getSortColumns().filter(function (el, i) {
            return el.columnId !== args.column.id;
          }));

			}else if(args.command === "sort-asc" || args.command === "sort-desc") {
        // get previously sorted columns
        // getSortColumns() only returns sortAsc & columnId, we want the entire column definition
        var oldSortColumns = grid.getSortColumns();
        var cols = $.map(oldSortColumns, function(col) {
          // get the column definition but only keep column which are not equal to our current column
          if(col.columnId !== args.column.id) {
            return {sortCol: columns[grid.getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
          }
				});

        // add to the column array, the column sorted by the header menu
				var isSortedAsc = (args.command === "sort-asc");
				cols.push({ sortAsc: isSortedAsc, sortCol: args.column });

				// update the grid sortColumns array which will at the same add the visual sort icon(s) on the UI
				newSortColumns = $.map(cols, function(col) {
					return {columnId: col.sortCol.id, sortAsc: col.sortAsc };
				});
				grid.setSortColumns(newSortColumns);
				executeSort(cols);
			}else {
				alert("Command: " + args.command);
			}
    });

    // subscribe to event when column visibility is changed via the menu
    columnpicker.onColumnsChanged.subscribe(function(e, args) {
	// Fix hidden sort column when multiColumnSort = true
	grid.setSortColumns(grid.getSortColumns().filter(function (el, i) {
          return args.columns.reduce(function(inc, c) {
            return inc + (el.columnId === c.id ? 1 : 0);
            }, 0) !== 0;
        }));	    
      console.log('Columns changed via the menu', args.columns);
    });

    grid.registerPlugin(headerMenuPlugin);

  })
</script>
</body>
</html>
